package com.mademoisellegeek.carrentalsimulation;

import com.mademoisellegeek.carrentalsimulation.enums.CarRentalExceptionType;

public class Garage implements Cloneable {

    private final int id;
    private final int totalSpaces;
    private final String town;
    private int[] occupiedSpaces = new int[365];

    public Garage(int id, String town, int totalSpaces, int initialNbParkedVehicles) {
        this.id = id;
        this.totalSpaces = totalSpaces;
        this.town = town;
        for (int i = 0; i < 365; i++) {
            this.occupiedSpaces[i] = initialNbParkedVehicles;
        }
    }

    public Garage(int id, String town, int totalSpaces, int[] occupiedSpaces) {
        this.id = id;
        this.totalSpaces = totalSpaces;
        this.town = town;
        this.occupiedSpaces = occupiedSpaces;
    }

    @Override
    public Object clone() {
        return new Garage(this.id, this.town, this.totalSpaces, this.occupiedSpaces);
    }

    public int getId() {
        return id;
    }

    public String getTown() {
        return town;
    }

    public int getOccupiedSpacesOnDay(int date) {
        return occupiedSpaces[date - 1];
    }

    public int getAvailableSpacesOnDay(int date) {
        return totalSpaces - occupiedSpaces[date - 1];
    }

    public int getMinAvailableSpacesFromDay(int date) {
        return totalSpaces - Utils.getMaxValueFrom(occupiedSpaces, date - 1);
    }

    public int getMinOccupiedSpacesFromDay(int date) {
        return Utils.getMinValueFrom(occupiedSpaces, date - 1);
    }

    public void saveHire(int date) throws CarRentalException {
        for (int i = date - 1; i < 365; i++) {
            if (occupiedSpaces[i] == 0){
                throw new CarRentalException(CarRentalExceptionType.SAVE_HIRE_FROM_EMPTY_GARAGE);
            }
            occupiedSpaces[i]--;
        }
    }

    public void saveReturn(int date) throws CarRentalException {
        for (int i = date; i < 365; i++) {
            if (occupiedSpaces[i] == totalSpaces) {
                throw new CarRentalException(CarRentalExceptionType.SAVE_RETURN_TO_FULL_GARAGE);
            }
            ++occupiedSpaces[i];
        }
    }

    @Override
    public String toString() {
        String garageString = "";
        garageString += "Garage number " + id + " in " + town + " has " + totalSpaces + " spaces";
        for (int i = 0; i < 365; i++) {
            if (i == 0 || (i > 0 && occupiedSpaces[i] != occupiedSpaces[i - 1])) {
                garageString += "Day " + (i + 1) + ": " + occupiedSpaces[i] + " occupied spaces";
            }
        }
        return garageString;
    }
}
